package com.example.desinger.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.desinger.common.R;
import com.example.desinger.designPattern.*;
import com.example.desinger.domain.dto.PageDto;
import com.example.desinger.entity.Students;
import com.example.desinger.mapper.StudentsMapper;
import com.example.desinger.service.StudentsService;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

@Service
public class StudentsServiceImpl extends ServiceImpl<StudentsMapper, Students> implements StudentsService {
    @Override
    public int selectByAccount(String account, int classId) {
        LambdaQueryWrapper<Students> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Students::getAccount, account).eq(Students::getClassId, classId);

        Students one = getOne(lambdaQueryWrapper);
        if (one == null) {
            return 0;
        }
        return 1;
    }

    @Override
    public R<Students> selectStudentByPAndW(Students students) {
        String account = students.getAccount();
        String password = students.getPassword();

        LambdaQueryWrapper<Students> lambdaQueryWrapper = new LambdaQueryWrapper();
        lambdaQueryWrapper.eq(Students::getAccount, account).eq(Students::getPassword, password);
        Students students1 = getOne(lambdaQueryWrapper);
        if (students1 != null) {
            return R.success(students1, "登录成功");
        }
        return R.error("登录失败");
    }

    @Override
    public R<PageDto<Students>> queryStudentsPage(int pageNo, int pageSize, int classId) {
        Page<Students> page = Page.of(pageNo, pageSize);
        Page<Students> studentsPage = lambdaQuery().eq(Students::getClassId, classId).page(page);

        PageDto<Students> dto = new PageDto<>();

        dto.setTotal(studentsPage.getTotal());

        dto.setPages(studentsPage.getPages());

        List<Students> records = studentsPage.getRecords();

        if (CollectionUtils.isEmpty(records)) {
            return R.success(dto, "查询成功但没有学生！");
        }

        dto.setList(records);

        return R.success(dto, "成功查询班级学生！");
    }

    @Override
    public ArrayList opertorGroup(int type, int classId) {
        // 分组操作
        // 1.查询班级的全部学生
        LambdaQueryWrapper<Students> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Students::getClassId, classId);
        List<Students> studentsList = list(lambdaQueryWrapper);

        GroupOperator groupOperator = new GroupOperator(studentsList, 17);

        // 策略模式
        if (type == 2) {
            // 性别优先排序
            groupOperator.setSplitGroupStratagem(new genderGroupStratagem());
        } else {
            // 随机分组
            groupOperator.setSplitGroupStratagem(new RandomGroupStratagem());
        }
        ArrayList data = groupOperator.group();

//        studentsList.forEach(System.out::println);

        //

        return data;
    }


    // 批量添加学生
    public R<String> addStudents(MultipartFile file, int classId) {
        // 读取文件
        // 分析，并存入 List 集合
//        List<Students> students = new ArrayList<>();

        List<Students> students = new ArrayList<>();
        String error = "";
        try (InputStream inputStream = file.getInputStream()) {
            Workbook workbook = WorkbookFactory.create(inputStream);
            Sheet sheet = workbook.getSheetAt(0); // Assuming the first sheet

            for (Row row : sheet) {
                if (row.getRowNum() == 0) {
                    // Skip header row
                    continue;
                }
                int serialNumber = (int) row.getCell(0).getNumericCellValue();
                String nickname = row.getCell(1).getStringCellValue();
                String account = row.getCell(2).getStringCellValue();
                int sex = (int) row.getCell(3).getNumericCellValue();

                // Build 模式
                Students student = new Students.Builder()
                        .withClassId(classId)
                        .withId(0)
                        .withAccount(account)
                        .withNickname(nickname)
                        .withPassword("123456")
                        .withSex(sex)
                        .build();

                students.add(student);
            }

            AddStudentsPipeFilter.PipeBase pipeA = new AddStudentsPipeFilter.PipeBase();
            AddStudentsPipeFilter.PipeBase pipeB = new AddStudentsPipeFilter.PipeBase();
            AddStudentsPipeFilter.PipeBase pipeError = new AddStudentsPipeFilter.PipeBase();

            AddStudentsPipeFilter.NullFilter nullFilter = new AddStudentsPipeFilter.NullFilter();
            AddStudentsPipeFilter.ValidFilter validFilter = new AddStudentsPipeFilter.ValidFilter();

            AddStudentsPipeFilter.FileterDecorator studentDecorator = new AddStudentsPipeFilter.FileterDecorator();
            for (Students student : students) {

                studentDecorator.setStudents(student);
                pipeA.setData(studentDecorator);
                nullFilter.filter(pipeA, pipeB, pipeError);
                validFilter.filter(pipeB, pipeA, pipeError);

                // 如果数据没有错误，保存到数据库
                if (pipeError.getData().getError().equals("")) {
                    save(student);
                } else {
                    error += pipeError.getData().getError() + ";";
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        if (!error.equals("")) {
            return R.error(error);
        }

        return R.success("添加成功！");


    }

}
